package cn.sumpu.app.guoguojie.domain;

import java.io.Serializable;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import cn.sumpu.app.guoguojie.util.Common;

public class OnLineUserListener implements HttpSessionBindingListener,Serializable {

	/** *  */
    private static final long serialVersionUID = -3000552362083904665L;
    public Member member = null;
    
	public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public OnLineUserListener(Member member) {
		this.member = member;
	}

	// @SuppressWarnings("unchecked")
	public void valueBound(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		// 把用户名放入在线列表
		// List<OnlineUser> onlineUserList = (List<OnlineUser>)
		// application.getAttribute("onlineUserList");
		// 第一次使用前，需要初始化
		// if (onlineUserList == null) {
		// onlineUserList = new ArrayList<OnlineUser>();
		// application.setAttribute("onlineUserList", onlineUserList);
		// }
		// OnlineUser user=new OnlineUser(this.member,new Date());
		//
		// onlineUserList.add(user);
		// System.out.println(this.member.getNickname() + "登录! ");

		// TODO 如果session占用的内存很大，需要做持久化
		String memberId = member.getIdentifier();
		application.setAttribute(memberId, session);
	}

	// @SuppressWarnings("unchecked")
	public void valueUnbound(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();// 从在线列表中删除用户名
		// List<OnlineUser> onlineUserList = (List<OnlineUser>)
		// application.getAttribute("onlineUserList");
		// if(null != onlineUserList && onlineUserList.size() > 0){
		// for(OnlineUser user:onlineUserList){
		// if(user.getMember().getIdentifier().equals(this.member.getIdentifier())){
		// System.out.println(this.member.getNickname() + "退出！退出时间"+new Date());
		// onlineUserList.remove(user);

		// TODO 删除session
		String memberId = member.getIdentifier();
		application.removeAttribute(memberId);
		// break;
		// }
		// }
		// }

	}
	public static Member getSessionMember(HttpServletRequest request){
	    OnLineUserListener onLineUserListener=(OnLineUserListener) request.getSession().getAttribute("onlineUser");
        if(Common.empty(onLineUserListener)){
            return null;
        }
	    return onLineUserListener.getMember();
	    
	}
}
